package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"gomicrodemo/proto/rand"
	"gomicrodemo/proto/user"
	"log"
	"net/http"
)

type APIHandler struct {
	randClient rand.RandService
	userClient user.UserService
}

//handler相当于grpc里面的controller
func GetAPIHandler(randService rand.RandService, userService user.UserService) *APIHandler {
	return &APIHandler{
		userClient: userService,
		randClient: randService,
	}
}

func (h APIHandler) Rand_POST(ctx *gin.Context) {

	//绑定参数到request
	request := &rand.RandRequest{}
	ctx.ShouldBindJSON(&request)

	//调用rpc服务
	response, err := h.randClient.GetRand(context.Background(), request)
	if err != nil {
		log.Println(err)
	}

	username, _ := ctx.Get("username")
	//使用gin框架返回结果值
	ctx.JSON(http.StatusOK, gin.H{
		"data":     response.Result,
		"username": username,
	})
}

func (h APIHandler) Rand_GET(c *gin.Context) {
	//name := c.Query("name")
	name := c.DefaultQuery("name", "tencentNIUBI")
	c.JSON(http.StatusOK, gin.H{
		"data": name,
	})
}

func (h APIHandler) UserRegistry(c *gin.Context) {

	request := &user.UserRegistryRequest{}
	c.ShouldBindJSON(&request)

	//调用user的rpc服务
	response, err := h.userClient.UserRegistry(context.Background(), request)
	if err != nil {
		panic(err)
	}

	c.JSON(http.StatusOK, gin.H{
		"data": response,
	})
}

func (h APIHandler) UserLogin(c *gin.Context) {

	//获取请求参数,绑定参数
	request := &user.UserLoginRequest{}
	c.ShouldBindJSON(request)

	//调用user的rpc服务
	response, err := h.userClient.UserLogin(c, request)
	if err != nil {
		log.Panicf("调用user的rpc服务失败，失败原因：", err)
	}

	requestId := c.Query("RequestId")
	c.JSON(http.StatusOK, gin.H{
		"data":      response,
		"requestId": requestId,
	})
}
